//
//  goodsViewController.m
//  随便点
//
//  Created by MWJ on 15/3/12.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "goodsViewController.h"
#import "MainTableViewCell.h"
#import <QuartzCore/QuartzCore.h>
#import "goodsTableViewCell.h"
#import "AppDelegate.h"
#import "dizliebiao.h"
#import "xiugaiViewController.h"
#define Kdizhi @"http://www.51anys.com:8080/waimaiwang/user/addressList"
#define SHANCHU @"http://www.51anys.com:8080/waimaiwang/user/deleteAddress"
@interface goodsViewController (){
    UILabel *_lab1;
    UILabel *_lab2;
    UIButton *_lab3;
    AppDelegate *app;
    NSMutableArray *array;
    NSMutableArray *lbarray;
    NSString *str;
    NSMutableArray *XSarray;
    NSString *Id;
    int defaultint;
    NSMutableArray * morenArray;
    NSString *strr;
    NSString *str1;
    NSString *str2;
    NSMutableArray *mrarray;
    
}

@end

@implementation goodsViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"zixingche"]]];
        self.navigationItem.title=@"收货地址管理";
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    mrarray = [NSMutableArray array];
    //tableView 顶端不出现空白
    self.automaticallyAdjustsScrollViewInsets=NO;
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    [self FirstRow];
    [self secondRow];
    [self loading];
    // Do any additional setup after loading the view.
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)loading{
    NSURL *url=[NSURL URLWithString:Kdizhi];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"userId=%@",app._id];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        array =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:array waitUntilDone:YES];
        lbarray = [NSMutableArray array];
        for (NSDictionary *obj in array){
            dizliebiao *lb = [[dizliebiao alloc]init];
            lb.name = obj[@"userId"];
            lb.phone = obj[@"mobile"];
            lb.streetName = obj[@"streetName"];
            lb.dizhiID = obj[@"id"];
            lb.Default = obj[@"isDefault"];
            [lbarray addObject:lb];
        }
        morenArray = [NSMutableArray array];
        for (NSInteger i = 0; i < lbarray.count; i ++) {
            NSDictionary *tempDic = array[i];
            if ([[NSString stringWithFormat:@"%@",tempDic[@"isDefault"]] isEqualToString:@"1"]) {
                [morenArray addObject:[NSString stringWithFormat:@"1"]];
            }else{
                [morenArray addObject:[NSString stringWithFormat:@"0"]];
            }
        }
        
        
        [self.tableview reloadData];
    }];
}
-(void)FirstRow{
    UILabel *lab1=[[UILabel alloc]init];
    CGFloat lab1X=10;
    CGFloat lab1Y=10;
    CGFloat lab1W=[UIScreen mainScreen].bounds.size.width-20;
    CGFloat lab1H=80;
    lab1.text = @"您必须选择一个地址作为当前的送货地址，如果还未添加收获地址，请点击新增按钮新增收获地址!";
    lab1.lineBreakMode = UILineBreakModeWordWrap;
    lab1.numberOfLines = 0;
    lab1.layer.borderWidth = 1;
    [lab1.layer setCornerRadius:10.0];
    lab1.textColor = [UIColor redColor];
    lab1.layer.borderColor = [[UIColor grayColor] CGColor];
    lab1.frame=CGRectMake(lab1X, lab1Y, lab1W, lab1H);
    _lab1=lab1;
}
-(void)secondRow{
    UILabel *lab2=[[UILabel alloc]init];
    CGFloat lab2X=10;
    CGFloat lab2Y=10;
    CGFloat lab2W=80;
    CGFloat lab2H=35;
    lab2.frame=CGRectMake(lab2X, lab2Y, lab2W, lab2H);
    lab2.text = @"新增地址";
    lab2.textColor = [UIColor greenColor];
    lab2.font=[UIFont boldSystemFontOfSize:15];
    _lab2 = lab2;
    
    UIButton *lab3=[[UIButton alloc]init];
    CGFloat lab3X=[UIScreen mainScreen].bounds.size.width-40;
    CGFloat lab3Y=10;
    CGFloat lab3W=31;
    CGFloat lab3H=31;
    lab3.frame=CGRectMake(lab3X, lab3Y, lab3W, lab3H);
    UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"add.png"]];
    [lab3 addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    [lab3 setBackgroundColor:color];
    _lab3 = lab3;
}
-(void)action:(UIGestureRecognizer *)sender{
    xiugaiViewController *xg = [self.storyboard instantiateViewControllerWithIdentifier:@"xgVC"];
    [self.navigationController pushViewController:xg animated:YES];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return lbarray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        UINib *nib=[UINib nibWithNibName:@"goodsTableViewCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"goodscell"];
        static NSString *cellIdentifier=@"goodscell";
        goodsTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[goodsTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        }
    
        dizliebiao *liebiao = lbarray[indexPath.row];
        cell.name.text = [NSString stringWithFormat:@"%@", liebiao.name];
        cell.phone.text = [NSString stringWithFormat:@"%@", liebiao.phone];
        cell.dizhi.text = [NSString stringWithFormat:@"%@",liebiao.streetName];
        cell.ID = str = [NSString stringWithFormat:@"%@",liebiao.dizhiID];
    [mrarray addObject:str];
    defaultint = [liebiao.Default intValue];
    
    if ([morenArray[indexPath.row] isEqualToString:@"0"]) {
        [cell.shezhi setTitleColor:[UIColor blueColor] forState:0];
    }
        else{
        [cell.shezhi setTitleColor:[UIColor grayColor] forState:0];
    }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.shezhi.tag = indexPath.row;
    [cell.shezhi addTarget:self action:@selector(shezhiAction:) forControlEvents:UIControlEventTouchUpInside];
    
        return cell;
}

- (void)shezhiAction:(id)butt{
    UIButton *tb = [[UIButton alloc]init];
    tb = (UIButton *)butt;
    array=[NSMutableArray array];
    strr = @"http://www.51anys.com:8080/waimaiwang/user/setDefault/";
    str1 = mrarray[tb.tag];
    str2 = [NSString stringWithFormat:@"%@%@",strr,str1];
    NSURL *url=[NSURL URLWithString:str2];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        array =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:array waitUntilDone:YES];
        }];

    for (NSInteger i = 0; i < morenArray.count; i ++) {
        if ([morenArray[i] isEqualToString:@"1"]) {
            [morenArray replaceObjectAtIndex:i withObject:@"0"];
        }
    }
    [morenArray replaceObjectAtIndex:tb.tag withObject:@"1"];
    [self.tableview reloadData];

    
}
-(void)refreshData{
         
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        dizliebiao *lb = lbarray[indexPath.row];
        Id = lb.dizhiID;
        [lbarray removeObjectAtIndex:indexPath.row];
        [self shanchu];
        [self.tableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else {
        NSLog(@"Unhandled editing style! %ld", editingStyle);
    }
}
-(void)shanchu{
    NSURL *url=[NSURL URLWithString:SHANCHU];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"id=%@",Id];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

-(void)gengg{
    app._dizhiID = str;
    
}
-(void)refreshData:(NSArray *)sender{
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)xinzeng:(id)sender {
    xiugaiViewController *xg = [self.storyboard instantiateViewControllerWithIdentifier:@"xgVC"];
    [self.navigationController pushViewController:xg animated:YES];
}
@end
